
package com.chy.utilsdemo.FileUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 功能： 文件上传工具类
 *
 * @author CHY
 */
@Repository
@Slf4j
public class FileUtils {

    @Value("${base.path.img-file}")
    private String diskPath;

    @Value("${base.path.img-file-url}")
    private String imgFileUrl;

    public String saveFile(MultipartFile multipartFile) {
        String no = IdGeneratorUtil.UUID32Generate();
        String name = multipartFile.getOriginalFilename();
        String[] names = name.split("\\.");
        String fileEnd = names[names.length - 1];
        log.info("name:{},names:{}",names,names);
        String pname = names[0]+"_"+no + "." + fileEnd;
        //String fileName=name.substring(0,name.lastIndexOf("."));
        //String fileType=name.substring(name.lastIndexOf("."));
        //String pname = fileName+"_"+no +  fileType;
        String diskUrl = diskPath + File.separator + pname;
        log.info("新增图片文件：" + diskUrl);
        File diskDir = new File(diskPath + File.separator + pname);
        if (!diskDir.getParentFile().exists()) {
            diskDir.getParentFile().mkdirs();
        }
        try (InputStream is = multipartFile.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(diskUrl))) {

            int num = 0;
            while ((num = bis.read()) != -1) {
                bos.write(num);
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("文件上传错误,请联系管理员");
        }
        return imgFileUrl + pname;

    }

    /**
     *
     * @param fileUrl 请求地址
     * @return int 删除结果  1  已删除  0 未删除
     */
    public int delFile(String fileUrl) {
        String[] routes = fileUrl.split("/");
        String fileDesk = diskPath + File.separator + routes[routes.length - 1];
        File file = new File(fileDesk);
        if (file.exists()) {
            file.delete();
            return 1;
        }
        return 0;
    }
}
